//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
// 引入SDK核心类,实例化API核心类
var QQMapWX = require('../../common/qqmap-wx-jssdk.js');
var demo = new QQMapWX({
  // 此key需要用户自己申请
  key: 'b6af1635786ff310b0f07cba63460532' // 必填
});
// 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    businessId: 0,
    imgUrl: baseJs.imgUrl,
    resultData: {},
    Businesslicense: [],
    describe: "",
    type: 0,
    threeType: 0,
    isAsc: false,
    pageIndex: 1,
    // 导航
    map: "",
    top: [{
      'title': '全部商品',
      'active': true,
      'type': 0
    },
    {
      'title': '分类',
      'active': false,
      'type': 2,
    },
    {
      'title': '商家介绍',
      'active': false,
      'type': 1,
    }

    ],
    threeData: [{
      'title': '销量',
      'active': true,
      'type': 0,
      'showBy': 'SaleNumber'
    },
    {
      'title': '最新',
      'active': false,
      'type': 1,
      'showBy': 'CreateTime'
    },
    {
      'title': '价格',
      'active': false,
      'type': 2,
      'showBy': 'PresentPrice'
    }
    ],
    swiperImgUrls: [],
    allGoodsData: [],
    state: '',
    showBy: 'SaleNumber',
    state: '',
    // 轮播设置
    indicatorDots: true,
    autoplay: true,
    autoplay: true,
    interval: 3000,
    indicatorActiveColor: "#fff",
    // 收藏商家
    color: '#999',
    // 
    uid: "",
    //支付
    buyType: "",
    modelStr: "",
    orderInfo: "",
    addCartOrNowBuy: "易码转账",
    goodsTypeList: [],//商品分类的数组
    SJID: "",//商家id
    SJTitle: "",//店铺名称
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      uid: wx.getStorageSync('uid'),
      businessId: options.businessId,
    })
    this.GetBusinessShopInfo();//获取商家信息
    this.CheckUserCollectionBusiness(); //收藏
    this.GetGoodsByBusinessID();
  },

  //刷新
  onRefresh() {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading({
      backgroundImage: 'http://coolui.coolwl.cn/assets/bg.jpg',
      title: '正在刷新...',
      show: true,
      // text: '下拉刷新',
      color: "#000000",
      shadow: 5
    });
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({

    })
    this.getData();
  },
  //网络请求，获取数据
  getData() {
    wx.request({
      url: '',
      //网络请求执行完后将执行的动作
      complete(res) {
        //隐藏loading 提示框
        wx.hideLoading();
        //隐藏导航条加载动画
        wx.hideNavigationBarLoading();
        //停止下拉刷新
        wx.stopPullDownRefresh();
      }
    })
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.pageIndex++;
    this.GetGoodsByBusinessID();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.SJTitle
    }
  },
  // 
  topTap: function (e) {
    var top = this.data.top;
    var type = e.currentTarget.dataset.type;
    for (var i = 0, len = top.length; i < len; ++i) {
      if (top[i].type == type) {
        top[i].active = true;
      } else {
        top[i].active = false
      }
    }
    this.setData({
      top: top,
      type: type
    })
    // console.log(type);
  },
  // 
  threeTap: function (e) {
    // console.log(e);
    var threeData = this.data.threeData;
    var threeTtype = e.currentTarget.dataset.type;
    var showBy = e.currentTarget.dataset.showby;
    for (var i = 0, len = threeData.length; i < len; ++i) {
      if (threeData[i].type == threeTtype) {
        threeData[i].active = true;
      } else {
        threeData[i].active = false
      }
    }
    this.setData({
      threeData: threeData,
      threeTtype: threeTtype,
      showBy: showBy
    })
    this.data.pageIndex = 1;
    this.data.allGoodsData = [];
    this.GetGoodsByBusinessID();
    // console.log(threeTtype,showBy);
  },
  // 获取商家信息
  GetBusinessShopInfo: function () {
    var that = this;
    var resultData = this.data.resultData;
    var businessId = this.data.businessId;
    var swiperImgUrls = this.data.swiperImgUrls;
    var Businesslicense = this.data.Businesslicense;
    var describe = this.data.describe;
    var map = this.data.map;
    var addCartOrNowBuy = this.data.addCartOrNowBuy;
    var SJID = this.data.SJID//商家id
    var SJTitle = this.data.SJTitle//商家店铺名称
    // console.log(baseJs.api_User + "GetBusinessShopInfo/" + businessId)
    wx.request({
      url: baseJs.api_User + "GetBusinessShopInfo/" + businessId,
      success: function (res) {
        resultData = res.data.ResultData;
        console.log(resultData);
        swiperImgUrls = resultData.ShopStorePic.split(";");
        Businesslicense = resultData.BusinesslicensePic.split(";");
        describe = resultData.Describe.replace(/<[^>]+>/g, "");
        SJID = resultData.Id
        SJTitle = resultData.BusinessAllName
        console.log(SJID);
        map = resultData.ShopProvinceName + resultData.ShopCityName + resultData.ShopDistinctName + resultData.BusinessAddress;
        that.setData({
          swiperImgUrls: swiperImgUrls,
          Businesslicense: Businesslicense,
          resultData: resultData,
          describe: describe,
          map: map,
          addCartOrNowBuy: addCartOrNowBuy,
          SJID: SJID,//商家id
          SJTitle: SJTitle,//店铺名称
        })
        wx.setNavigationBarTitle({
          title: resultData.BusinessAllName
        })
        that.GetGoodsType()//获取分类的数据
      }
    })
  },
  // 全部商品
  GetGoodsByBusinessID: function () {
    var that = this;
    var businessId = this.data.businessId;
    var isAsc = this.data.isAsc;
    var pageIndex = this.data.pageIndex;
    var showBy = this.data.showBy;
    var state = this.data.state;
    var allGoodsData = this.data.allGoodsData;
    // if (pageIndex == 1) {
    //   wx.showLoading({
    //     title: '加载中',
    //   })
    // }
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetGoodsByBusinessID&BID=" + businessId + "&PageSize=10&PageIndex=" + pageIndex + "&IsAsc=" + isAsc + "&OrderBy=" + showBy),
      // url: baseJs.api + baseJs.encryUrl("method=GetGoodsByBusinessID&BID=" + uid + "&PageSize=2000&PageIndex=" + pageIndex + "&IsAsc=" + isAsc + "&OrderBy=" + showBy),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        console.log(json);
        for (var i = 0; i < json.length; i++) {
          allGoodsData.push(json[i])
        }
        that.setData({
          allGoodsData: allGoodsData,
        })

        if (json.length == 10) {
          that.setData({
            state: 'loadMore',
          })
        } else if (json.length == 0 && pageIndex == 1) {
          that.setData({
            state: 'noData',
          })
        } else if (json.length < 10) {
          that.setData({
            state: 'noMore',
          })
        } else if (json.length == 0 && pageIndex > 1) {
          that.setData({
            state: 'noMore',
          })
        }
        wx.hideLoading();
        // console.log(state);
        // console.log(allGoodsData);
        // console.log(baseJs.api + "method=GetGoodsByBusinessID&BID=" + businessId + "&PageSize=10&PageIndex=" + pageIndex + "&IsAsc=" + isAsc + "&OrderBy=" + showBy);
      }
    })
  },
  // 
  phoneCall: function () {
    var that = this;
    var resultData = this.data.resultData;
    var phoneNumber = resultData.MobilePhone;
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },
  // 收藏
  CheckUserCollectionBusiness: function () {
    var that = this;
    var uid = this.data.uid;
    var businessId = this.data.businessId;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=CheckUserCollectionBusiness&UID=" + uid + "&BID=" + businessId),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)))
        if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
          that.setData({
            color: "#f00",
          })
        } else {
          that.setData({
            color: "#999",
          })
        }
      }
    })
  },
  // 
  collectTap: function () {
    if (app.isLogin()) {
      var that = this;
      var uid = this.data.uid;
      var businessId = this.data.businessId;
      wx.request({
        url: baseJs.api + baseJs.encryUrl("method=AddBusinessCollection&UID=" + uid + "&SJId=" + businessId),
        success: function (res) {
          console.log(JSON.parse(baseJs.decryUrl(res.data)));
          if (JSON.parse(baseJs.decryUrl(res.data)).ResultMsg == '设置优选商家成功') {
            wx.showToast({
              title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
              icon: 'none',
              duration: 800,
              mask: false
            })
            that.setData({
              color: "#f00",
            })
          } else {
            wx.showToast({
              title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
              icon: 'none',
              duration: 800,
              mask: false
            })
            that.setData({
              color: "#999",
            })
          }
        }
      })
    }
  },
  // 商家地址导航 
  openMap: function () {
    var that = this;
    var map = this.data.map;
    // 调用接口
    demo.geocoder({
      address: map,
      success: function (res) {
        console.log(res);
        wx.openLocation({
          latitude: res.result.location.lat,
          longitude: res.result.location.lng,
          scale: 28
        })
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },


  // 店铺
  storeTap: function () {
    var that = this;
    var businessId = this.data.businessId;
    wx.navigateTo({
      url: '/packageA/store/store?businessId=' + businessId,
    })
  },
  // 兑换电话
  phoneCall: function () {
    var that = this;
    var resultData = this.data.resultData;
    var phoneNumber = resultData.DuihuanPhone;
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },
  // 投诉
  complaint: function () {
    if (app.isLogin()) {
      var that = this;
      var businessId = this.data.businessId;
      wx.navigateTo({
        url: '/packageA/complaint/complaint?businessId=' + businessId,
      })
    }
  },

  //点击立刻购买跳转到易码转账页面
  freepay: function () {
    var that = this;
    var uid = wx.getStorageSync('uid');
    var userType = this.data.userType;
    userType = wx.getStorageSync('userType');
    this.setData({
      uid: uid,
      userType: userType,
    })
    if (!uid) {
      // 暂时注释：
      wx.showModal({
        title: '提示',
        content: '请先登录易易部落！',
        showCancel: true,
        confirmText: "确定",
        success: function (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/packageA/login/login',
            })
          } else {
          }
        },
      })
    } else {
      wx.navigateTo({
        url: '/packageA/freePay/freePay?businessId=' + that.data.businessId,
      })
    }

  },
  //点击收银机跳转到收银机-我的产品 页面
  myProduct: function () {
    // SJId
    var that = this;
    wx.navigateTo({
      url: '/packageA/myProduct/myProduct?businessId=' + that.data.businessId,
    })

  },

  // 获取分类列表
  GetGoodsType: function () {
    var that = this
    console.log(that.data.SJID);
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=BusinessGetCustomGoodsType&UID=" + that.data.SJID + "&Type=1"),
      success: (res) => {
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        console.log(json);
        this.setData({
          goodsTypeList: json
        })
      }
    })
  },
  // 跳转分类详情页面
  ListLook(e) {
    var index=e.currentTarget.dataset.index
    var name=e.currentTarget.dataset.name
    wx.navigateTo({
      url: '/packageA/uploadGoodsList/uploadGoodsList?TypeId=' + index+"&SJID="+this.data.SJID+"&name="+name,//我的产品
    })
  },

})